package com.web.exiaodao.remote.controller;

import java.util.Map;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.web.exiaodao.remote.service.*;
import com.web.exiaodao.remote.vo.CheckInRuleVo;
import com.web.exiaodao.remote.vo.LotteryRuleVo;
import com.web.exiaodao.remote.vo.MakeMoneyTableVo;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.XaUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.exiaodao.remote.vo.CheckInTableVo;
import com.web.exiaodao.business.entity.CheckInTable;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiCheckInTableController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 签到-抽奖-接口
 * @date 2015年3月23日 下午1:00:00
 */
@Api(value = "CheckInTable", description = "签到/抽奖/亲币管理接口", position = 10)
@Controller
@RequestMapping("/api/checkInTable")
public class ApiCheckInTableController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiCheckInTableController.class);

    @Autowired
    private ApiCheckInTableService checkInTableService;

    @Autowired
    private ApiUserService userService;

    @Autowired
    private ApiLotteryRuleService lotteryRuleService;

    @Autowired
    private ApiMakeMoneyTableService makeMoneyTableService;

    @Autowired
    private ApiCheckInRuleService checkInRuleService;

    /**
     * @return
     * @Title: findCheckInTableList
     * @Description: 查询签到-签到表信息最新的一条
     */
    @ApiOperation(value = "查询今日的签到信息", notes = "查询今日的签到信息,当返回的code=1时，取出object进行显示,存放为单个对象")
    @ResponseBody
    @RequestMapping(value = "findCheckInfo", method = RequestMethod.POST)
    public XaResult<CheckInTableVo> findCheckInTableList(
            @ApiParam("签到人ID,字段名:userId") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<CheckInTableVo> xr = new XaResult<>();
        try {
            //验证用户是否存在
            userService.findOne(userId);
            return checkInTableService.findLastOne(userId);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else  {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(xr.getMessage(), new Throwable(e));
        }
        return xr;
    }


    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     * //@param userId
     * //@param model
     */
    @ApiOperation(value = "新增今日签到", notes = "新增签到-签到,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveCheckInTable", method = RequestMethod.POST)
    public XaResult<CheckInTableVo> saveCheckInTable(
            @ApiParam("用户id,字段名:userId") @RequestParam(value = "userId") Long userId,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<CheckInTableVo> xr = new XaResult<CheckInTableVo>();
        if(XaUtil.isEmpty(userId)){
            xr.error("userId不能为空");
            return xr;
        }
        String checkIn_DateTime = DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS);
        try {
            //验证用户是否存在
            userService.findOne(userId);

            //验证今天是否已经签到
            xr  = checkInTableService.findLastOne(userId);
            Long checkIdLong = xr.getObject().getId();
            if (xr.getObject() instanceof CheckInTableVo && checkIdLong != null) {
                xr.error("你已经签到,谢谢,请不要重复签到");
                return xr;
            }

            //计算昨天签到次数
            long check_Count = checkInTableService.calculateCheckTimesYesterday(userId).getObject();

            CheckInTable model = new CheckInTable();
            model.setUserId(userId);
            model.setCheckIn_DateTime(checkIn_DateTime);
            model.setCheck_Count(check_Count);
            return checkInTableService.createModel(model);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else  {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(xr.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @Title: findLotteryRuleList
     * @Description: 查询所有签到-超级转一转规则信息
     * @return
     */
    @ApiOperation(value="查询超级转一转规则信息",notes="查询超级转一转规则信息,正常只有12条规则,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value="findLotteryRuleList",method=RequestMethod.POST)
    public XaResult<List<LotteryRuleVo>> findLotteryRuleList(
    ) throws BusinessException{
        Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Map<String , Object> filterParams =  WebUitl.getParametersStartingWith("{}", "search_");
        return lotteryRuleService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
    }

    /**
     * @Title: findLotteryRuleList
     * @Description: 查询所有签到-超级转一转规则信息
     * @return
     */
    @ApiOperation(value="抽奖接口",notes="抽奖接口")
    @ResponseBody
    @RequestMapping(value="drawLottery",method=RequestMethod.POST)
    public XaResult<LotteryRuleVo> drawLottery(
            @ApiParam("用户ID,字段名:userId") @RequestParam(value = "userId") Long userId
    ) throws BusinessException{
        XaResult<LotteryRuleVo> xr = new XaResult<>();
        try {
            xr = lotteryRuleService.drawLottery(userId);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else  {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(xr.getMessage(), new Throwable(e));
        }
        return xr;
    }

    /**
     * @Title: findMakeMoneyTableList
     * @Description: 查询所有签到-孝亲币管理信息
     * @return
     */
    @ApiOperation(value="查询所有孝亲币信息列表",notes="查询所有签到-孝亲币管理信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value="findMakeMoneyTableList",method=RequestMethod.POST)
    public XaResult<List<MakeMoneyTableVo>> findMakeMoneyTableList(
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("赚钱还是消费（-1:消费；1:赚钱, 不填是所有）,字段名:consumeOrMakeMoney") @RequestParam(value = "consumeOrMakeMoney", required = false) Integer consumeOrMakeMoney
    ) throws BusinessException{
        XaResult<List<MakeMoneyTableVo>> xr = new XaResult<>();
        if ( consumeOrMakeMoney != null &&  !(consumeOrMakeMoney == 1 | consumeOrMakeMoney == -1) ) {
            xr.error("consumeOrMakeMoney参数错误");
            return xr;
        }
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String , Object> filterParams = WebUitl.getParametersStartingWith("{}", "search_");
        if (consumeOrMakeMoney != null) {
            filterParams = WebUitl.getParametersStartingWith("{'search_EQ_consumeOrMakeMoney':'" + consumeOrMakeMoney + "'}", "search_");
        }
        xr = makeMoneyTableService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
        return xr;
    }


    /**
     * @return
     * @Title: findCheckInRuleList
     * @Description: 查询所有签到-亲币规则说明信息
     */
    @ApiOperation(value = "查询所有亲币规则说明", notes = "查询所有签到-亲币规则说明信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findCheckInRuleList", method = RequestMethod.POST)
    public XaResult<List<CheckInRuleVo>> findCheckInRuleList(
            @ApiParam("赚钱还是消费（-1:亲币使用；1:获取亲币, 不填是所有）,字段名:consumeOrMakeMoney") @RequestParam(value = "consumeOrMakeMoney", required = false) Integer consumeOrMakeMoney
    ) throws BusinessException {
        XaResult<List<CheckInRuleVo>> xr = new XaResult<>();
        if (consumeOrMakeMoney != null && !(consumeOrMakeMoney.intValue() == 1 || consumeOrMakeMoney.intValue() == -1)) {
            xr.error("consumeOrMakeMoney参数不正确");
            return xr;
        }
        Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{'search_EQ_consumeOrMakeMoney':'" + consumeOrMakeMoney + "'}", "search_");
        if (consumeOrMakeMoney == null) {
            filterParams.clear();
        }
        return checkInRuleService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
    }
}

